package br.com.fpf.pontoapp.ws.impl;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

import android.util.Log;

/**
 * The Class NewConnection.
 * 
 * @author irlan.gomes
 */
class NewConnection {

	/** The request. */
	private static String request = "http://www.ahgora.com.br/batidas/entrar/ajax";

	//TODO deixar o mes dinamico
	/** The url batidas. */
	private static String urlBatidas = "http://www.ahgora.com.br/batidas/ver/10-2013";

	/** The connection. */
	private static HttpURLConnection connection;

	/** The Constant OPONTO. */
	private static final String OPONTO = "OPONTO";

	/** The html. */
	private String html;

	/**
	 * Instantiates a new new connection.
	 * 
	 * @param login
	 *            the login
	 * @param password
	 *            the password
	 */
	public NewConnection(String login, String password) {
		html = getHtml(login, password);
	}

	/**
	 * Gets the html.
	 * 
	 * @return the html
	 */
	public String getHtml() {
		return html;
	}

	/**
	 * Gets the html.
	 * 
	 * @param login
	 *            the login
	 * @param password
	 *            the password
	 * @return the html
	 */
	private String getHtml(String login, String password) {
		StringBuffer response = new StringBuffer();
		try {

			String contentPost = getContentPost(login, password);

			// Create connection
			URL url = new URL(request);

			getConnection(contentPost, url);

			// Send request
			sendResquest(contentPost);

			// Get Response
			InputStream inputStream = connection.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					inputStream));
			String line;

			while ((line = reader.readLine()) != null) {
				response.append(line);
				response.append('\r');
			}
			reader.close();

			System.out.println(response.toString());

			String sessionCookie = getSessionCookie();

			url = new URL(urlBatidas);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestProperty("Cookie", sessionCookie);

			// Pega a resposta
			inputStream = connection.getInputStream();
			reader = new BufferedReader(new InputStreamReader(inputStream));
			response = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				response.append(line);
				response.append('\r');
			}
			reader.close();

		} catch (ProtocolException e) {
			Log.d(OPONTO, e.getMessage());

		} catch (IOException e) {
			Log.d(OPONTO, e.getMessage());

		} finally {
			closeConnection();

		}

		return response.toString();
	}

	/**
	 * Gets the content post.
	 * 
	 * @param matricula
	 *            the matricula
	 * @param senha
	 *            the senha
	 * @return the content post
	 */
	private static String getContentPost(String matricula, String senha) {
		StringBuilder contentPost = new StringBuilder();
		contentPost.append("dados[empresa]=a665612&dados[matricula]=");
		contentPost.append(matricula);
		contentPost.append("&dados[senha]=");
		contentPost.append(senha);
		return contentPost.toString();
	}

	/**
	 * Gets the connection.
	 * 
	 * @param contentPost
	 *            the content post
	 * @param url
	 *            the url
	 * @return the connection
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 * @throws ProtocolException
	 *             the protocol exception
	 */
	private static void getConnection(String contentPost, URL url)
			throws IOException, ProtocolException {
		connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		connection.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");

		connection.setRequestProperty("Content-Length",
				Integer.toString(contentPost.getBytes().length));
		connection.setUseCaches(false);
		connection.setDoInput(true);
		connection.setDoOutput(true);
	}

	/**
	 * Send resquest.
	 * 
	 * @param contentPost
	 *            the content post
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	private static void sendResquest(String contentPost) throws IOException {
		DataOutputStream outputStream = new DataOutputStream(
				connection.getOutputStream());
		outputStream.writeBytes(contentPost.toString());
		outputStream.flush();
		outputStream.close();
	}

	/**
	 * Gets the session cookie.
	 * 
	 * @return the session cookie
	 */
	private static String getSessionCookie() {
		String sessionCookie = null;
		String headerName;
		for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
			if (headerName.equalsIgnoreCase("Set-Cookie")) {
				if (sessionCookie == "") {
					sessionCookie = connection.getHeaderField(i);
				} else {
					sessionCookie += "; " + connection.getHeaderField(i);
				}
			}
		}
		return sessionCookie;
	}

	/**
	 * Close connection.
	 */
	private static void closeConnection() {
		if (connection != null) {
			connection.disconnect();
		}
	}

}
